// grass/pages/grassGoods/grassGoods.js
var common = require("../../../common/common.js").common;

var shoppingCar = require("../../../common/shoppingCar.js");

var util = require("../../../utils/util.js");

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        goods: []
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        wx.hideShareMenu();
        //隐藏转发分享按钮
                let pagesLength = getCurrentPages().length;
        var isIPX = app.globalData.isIPX;
        this.setData({
            isIPX: isIPX,
            pagesLength: pagesLength
        });
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        let that = this;
        that.getBase();
        common.getCart();
        if (that.data.goods.length > 0) {
            var newPro = that.changeProInfo(that.data.goods);
            var newShoppingCart = shoppingCar.getInfo();
            that.setData({
                cart_count: newShoppingCart.cart_count,
                goods: newPro
            });
        }
    },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {
        wx.stopPullDownRefresh();
    },
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {},
    //全局基础配置信息
    getBase: function(openid) {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                that.setData({
                    color_header: res.extra.color_header,
                    color_text: res.extra.color_text,
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor
                });
            }
        });
    },
    /*购物车开始*/
    join_cart: function(e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        let single = e.currentTarget.dataset.single;
        common.request({
            // endpoint: 'product/product_info',
            endpoint: "product/shopping-push",
            method: "post",
            data: {
                id: id
            },
            success: res => {
                let details = res.extra;
                details.sku_attribute = details.sku_attribute.map(item => {
                    item.attribute_value = this.selectSingleSku(item.attribute_value);
                    return item;
                });
                let sku_attribute = details.sku_attribute;
                let sku = sku_attribute.reduce((s, v) => {
                    s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
                    return s;
                }, "");
                let sku_info = this.getProductBySku(details.sku, sku);
                let cart_count = wx.getStorageSync("cart_count");
                if (single == 1) {
                    that.join_cart_ch(details, e);
                    if (that.data.subscribeMessage) {
                        wx.requestSubscribeMessage({
                            tmplIds: that.data.tmplIds,
                            success(res) {},
                            fail(err) {
                                console.log(err);
                            }
                        });
                    }
                } else {
                    that.setData({
                        details: details,
                        sku: sku,
                        alert: 1,
                        product_id: id,
                        sku_info: sku_info,
                        proId: id,
                        buy_count: 1
                    });
                }
            }
        });
    },
    //单规格购买
    join_cart_ch: function(details, e) {
        var that = this;
        var id = e.currentTarget.dataset.id;
        let single = e.currentTarget.dataset.single;
        details.sku_attribute = details.sku_attribute.map(item => {
            item.attribute_value = this.selectSingleSku(item.attribute_value);
            return item;
        });
        let sku_attribute = details.sku_attribute;
        let sku = sku_attribute.reduce((s, v) => {
            s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
            return s;
        }, "");
        let sku_info = this.getProductBySku(details.sku, sku);
        let cart_count = wx.getStorageSync("cart_count");
        if (cart_count <= 99999) {
            if (sku_info.stock_number >= 1) {
                wx.showToast({
                    title: "加入购物车成功",
                    icon: "none",
                    success: res => {
                        let goods = {
                            id: sku_info.item_id,
                            product_id: id,
                            img: details.icon_img,
                            title: details.name,
                            varieties: sku_info.title,
                            price: sku_info.price,
                            o_price: sku_info.o_price,
                            count: 1,
                            stock_number: sku_info.stock_number,
                            select: 1,
                            proID: id,
                            status: 1,
                            credit_sent: sku_info.credit_sent || 0
                        };
                        let newShoppingCart = shoppingCar.addPro(goods);
                        var newGoods = that.changeProInfo(that.data.goods, newShoppingCart);
                        that.setData({
                            goods: newGoods,
                            cart_count: newShoppingCart.cart_count
                        });
                        that.changeIconNum(newShoppingCart.cart_count, 2);
                    }
                });
            } else {
                wx.showToast({
                    title: "库存不足",
                    icon: "none"
                });
            }
        } else {
            wx.showToast({
                title: "购物车最多加99999个商品！",
                icon: "none"
            });
        }
    },
    /** 
   * 添加 sku 属性
   */
    addSkuAttribute: function(e) {
        let key_id = parseInt(e.currentTarget.dataset.key_id);
        let value_id = parseInt(e.currentTarget.dataset.value_id);
        let a_key_index = parseInt(e.currentTarget.dataset.a_key_index);
        let a_value_index = parseInt(e.currentTarget.dataset.a_value_index);
        let sku = this.data.sku;
        sku = this.reBlanceSku(sku, key_id, value_id);
        let attribute = this.data.details.sku_attribute;
        attribute = this.selectSku(attribute, a_key_index, a_value_index);
        let sku_info = this.getProductBySku(this.data.details.sku, sku);
        this.setData({
            sku: sku,
            ["details.sku_attribute"]: attribute,
            sku_info: sku_info
        });
    },
    /** 
    * 重平衡 sku
    * key_id: integer
    */
    reBlanceSku: function(sku, key_id, value_id) {
        let sku_lib = sku != "" ? this.splitSku(sku) : [];
        sku_lib = this.addSku(sku_lib, {
            key_id: key_id,
            value_id: value_id
        });
        sku_lib = this.sortSku(sku_lib);
        return this.buildSku(sku_lib);
    },
    /** 
 * 重建 sku
 */
    buildSku: function(sku_lib) {
        return sku_lib.map(item => {
            return item.key_id + "," + item.value_id;
        }).join("|");
    },
    /** 
   * 对选择的 sku 属性进行排序
   */
    sortSku: function(sku_lib) {
        return sku_lib.sort((pre, next) => {
            if (pre.key_id > next.key_id) {
                return 1;
            } else if (pre.key_id < next.key_id) {
                return -1;
            } else {
                return 0;
            }
        });
    },
    /** 
   * 分割现有 sku 成对象数组
   */
    splitSku: function(sku) {
        return sku.split("|").map(sku_tmp => {
            let [key, value] = sku_tmp.split(",");
            const t = {};
            t.key_id = parseInt(key);
            t.value_id = parseInt(value);
            return t;
        });
    },
    /** 
  * 添加一个 sku
  */
    addSku: function(sku_lib, sku) {
        let t = sku_lib.filter(item => {
            if (item.key_id === sku.key_id) {
                return false;
            }
            return true;
        });
        t.push(sku);
        return t;
    },
    /** 
   * 选择 sku
   */
    selectSku: function(attribues, a_index, v_index = 0) {
        if (attribues[a_index]) {
            let values = attribues[a_index].attribute_value;
            values = values.map(item => {
                item.selected = false;
                return item;
            });
            values[v_index].selected = true;
            attribues[a_index].attribute_value = values;
        }
        return attribues;
    },
    /** 
   * 选择单个 sku 属性
   */
    selectSingleSku: function(attribute_value, v_index = 0) {
        attribute_value.map(item => {
            item.selected = false;
            return item;
        });
        attribute_value[v_index].selected = true;
        return attribute_value;
    },
    save_count: function(e) {
        this.setData({
            buy_count: parseInt(e.detail.value)
        });
    },
    reduce_count: function() {
        let buy_count = this.data.buy_count;
        if (buy_count > 1) {
            buy_count--;
        }
        this.setData({
            buy_count: buy_count
        });
        this.changeIconNum(buy_count, 2);
    },
    add_count: function(e) {
        let that = this;
        that.add_count_ch(e);
        if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {},
                fail(err) {
                    console.log(err);
                }
            });
        }
    },
    add_count_ch: function(e) {
        let buy_count = this.data.buy_count;
        let restrictions = e.currentTarget.dataset.restrictions;
        if (restrictions == 0) {
            buy_count++;
        } else {
            if (buy_count >= restrictions) {
                wx.showModal({
                    title: "提示",
                    content: "本商品限购" + restrictions + "份"
                });
            } else {
                buy_count++;
            }
        }
        this.setData({
            buy_count: buy_count
        });
        this.changeIconNum(buy_count, 2);
    },
    /**
   * 根据 sku 获取物品
   */
    getProductBySku: function(sku_products, sku) {
        return sku_products[sku];
    },
    join_goods: function() {
        let that = this;
        that.join_goods_ch();
        if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {},
                fail(err) {
                    console.log(err);
                }
            });
        }
    },
    // 加入购物车
    join_goods_ch: function() {
        var that = this;
        var cart_count = wx.getStorageSync("cart_count") || 0;
        var details = that.data.details;
        var sku_info = that.data.sku_info;
        var buy_count = that.data.buy_count;
        var sku_id = that.data.product_id;
        var proId = that.data.proId;
        var cart = wx.getStorageSync("cart") || [];
        cart_count = cart_count + buy_count;
        if (cart_count <= 99999) {
            if (sku_info.stock_number >= buy_count) {
                if (cart == "") {
                    let goods = {
                        id: sku_info.item_id,
                        product_id: sku_id,
                        img: details.icon_img,
                        title: details.name,
                        varieties: sku_info.title,
                        price: sku_info.price,
                        o_price: sku_info.o_price,
                        count: buy_count,
                        stock_number: sku_info.stock_number,
                        select: 1,
                        proId: proId,
                        status: 1
                    };
                    wx.showToast({
                        title: "加入购物车成功",
                        icon: "success",
                        success: res => {
                            wx.setStorage({
                                key: "cart_count",
                                data: cart_count
                            });
                            var cart = wx.getStorageSync("cart") || that.data.cart;
                            cart.push(goods);
                            wx.setStorage({
                                key: "cart",
                                data: cart
                            });
                            this.setData({
                                cart_count: cart_count
                            });
                            this.changeIconNum(cart_count, 2);
                            setTimeout(() => {
                                let newShoppingCart = shoppingCar.getInfo();
                                var newPro = that.changeProInfo(that.data.goods, newShoppingCart);
                                that.setData({
                                    buy_count: 1,
                                    alert: 0,
                                    goods: newPro
                                });
                            }, 500);
                        }
                    });
                } else {
                    var total = 0;
                    var index = 0;
                    for (var i = 0; i < cart.length; i++) {
                        if (sku_info.item_id != cart[i]["id"]) {
                            total++;
                        } else {
                            index = i;
                            break;
                        }
                    }
                    if (total == cart.length) {
                        let goods = {
                            id: sku_info.item_id,
                            product_id: sku_id,
                            img: details.icon_img,
                            title: details.name,
                            varieties: sku_info.title,
                            price: sku_info.price,
                            o_price: sku_info.o_price,
                            count: buy_count,
                            stock_number: sku_info.stock_number,
                            select: 1,
                            proId: proId,
                            status: 1
                        };
                        wx.showToast({
                            title: "加入购物车成功",
                            icon: "success",
                            success: res => {
                                wx.setStorage({
                                    key: "cart_count",
                                    data: cart_count
                                });
                                var cart = wx.getStorageSync("cart") || that.data.cart;
                                cart.push(goods);
                                wx.setStorage({
                                    key: "cart",
                                    data: cart
                                });
                                this.setData({
                                    cart_count: cart_count
                                });
                                this.changeIconNum(cart_count, 2);
                                setTimeout(() => {
                                    let newShoppingCart = shoppingCar.getInfo();
                                    var newPro = that.changeProInfo(that.data.goods, newShoppingCart);
                                    that.setData({
                                        buy_count: 1,
                                        alert: 0,
                                        goods: newPro
                                    });
                                }, 500);
                            }
                        });
                    } else {
                        cart[index]["count"] = cart[index]["count"] + buy_count;
                        wx.showToast({
                            title: "加入购物车成功",
                            icon: "success",
                            success: res => {
                                wx.setStorage({
                                    key: "cart_count",
                                    data: cart_count
                                });
                                wx.setStorage({
                                    key: "cart",
                                    data: cart
                                });
                                this.setData({
                                    cart_count: cart_count
                                });
                                this.changeIconNum(cart_count, 2);
                                setTimeout(() => {
                                    let newShoppingCart = shoppingCar.getInfo();
                                    var newPro = that.changeProInfo(that.data.goods, newShoppingCart);
                                    that.setData({
                                        buy_count: 1,
                                        alert: 0,
                                        goods: newPro
                                    });
                                }, 500);
                            }
                        });
                    }
                }
            } else {
                wx.showToast({
                    title: "加入购物车失败",
                    icon: "none"
                });
            }
        } else {
            wx.showToast({
                title: "购物车最多加99999个商品！",
                icon: "none"
            });
        }
    },
    /**
 * 商品信息修改
*/
    changeProInfo(proInfo, carInfoParamter) {
        var cartInfo = carInfoParamter ? carInfoParamter.statisticsArry : shoppingCar.getInfo().statisticsArry;
        if (proInfo.length > 0) {
            proInfo.forEach((item, index) => {
                if (cartInfo.length > 0) {
                    for (var i = 0; i < cartInfo.length; i++) {
                        if (item.id == cartInfo[i].product_id) {
                            item.buyCount = cartInfo[i].count;
                            break;
                        } else {
                            item.buyCount = 0;
                        }
                    }
                } else {
                    item.buyCount = 0;
                }
            });
        }
        return proInfo;
    },
    reduceCount(e) {
        let that = this;
        if (e.currentTarget.dataset.single == 1) {
            var newShoppingCart = shoppingCar.reducePro([ e.currentTarget.dataset.id ]);
            var newPro = that.changeProInfo(that.data.goods, newShoppingCart);
            that.setData({
                cart_count: newShoppingCart.cart_count,
                goods: newPro
            });
            that.changeIconNum(newShoppingCart.cart_count, 2);
        } else {
            wx.showToast({
                title: "该商品是多属性商品，请到购物车操作",
                icon: "none"
            });
        }
    },
    addCount(e) {
        let that = this;
        that.join_cart(e);
    },
    //获取tmplIds
    getTmplIds: function() {
        let that = this;
        const version = wx.getSystemInfoSync().SDKVersion;
        //console.log(version);
                if (util.compareVersion(version, "2.8.2") < 0) {
            that.setData({
                tmplIds: [],
                subscribeMessage: false
            });
            return;
        }
        common.request({
            endpoint: "set/template_get",
            method: "post",
            data: {},
            header: {
                "content-type": "application/json"
            },
            success: res => {
                console.log(res);
                let tmplIds = [];
                let subscribeMessage = true;
                res.extra.map(v => {
                    if ((v.type == "21" || v.type == "22" || v.type == "23") && v.status == "1") {
                        tmplIds.push(v.template_id);
                    }
                });
                if (!tmplIds.length) {
                    subscribeMessage = false;
                }
                that.setData({
                    tmplIds: tmplIds,
                    subscribeMessage: subscribeMessage
                });
            }
        });
    },
    /**
    * 改变购物车上标数字
   */
    changeIconNum(num, index) {
        let that = this;
        var tabBar = that.data.tabBar;
        tabBar[index].num = num;
        that.setData({
            tabBar: tabBar
        });
    }
});